package com.example.leetcode.day;

import java.util.ArrayList;
import java.util.List;

/**
 * 给你一个 m 行 n 列的矩阵 matrix ，请按照 顺时针螺旋顺序 ，返回矩阵中的所有元素。
 */
public class Day54 {


    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<>();
        if (matrix == null || matrix.length == 0 || matrix[0].length==0){
            return result;
        }
        int m = matrix.length;
        int n = matrix[0].length;
        int left = 0,right = n-1,top = 0,last =m-1;
        while (left<=right && top<=last){
            for (int i =left;i<=right;i++){
                result.add(matrix[top][i]);
            }
            for (int j = top+1;j<=last;j++){
                result.add(matrix[j][right]);
            }
            if (left<right && top<last){
                for (int i = right-1;i>left;i--){
                    result.add(matrix[last][i]);
                }
                for (int j = last;j>top;j--){
                    result.add(matrix[j][left]);
                }
            }
            left++;
            right--;
            top++;
            last--;
        }
        return result;
    }

    public static void main(String[] args) {
        Day54 d = new Day54();
        int[][] t = {{7},{9},{6}};
        System.out.println(d.spiralOrder(t));
    }
}
